<template>
  <a-modal
    :title="folderInfo ? '更新文件夹' : '新增文件夹'"
    :visible="true"
    destroyOnClose
    @ok="handleOk"
    @cancel="$emit('close-modal')"
    :confirmLoading="requestLoading"
    okText="确定"
    cancelText="取消"
  >
    <a-form-model
      :model="form"
      :rules="formRules"
      ref="ruleForm"
      labelAlign="left"
      :label-col="{ span: 5 }"
      :wrapperCol="{ span: 18 }">
      <a-form-model-item label="文件夹名称" prop="name">
        <a-input v-model="form.name" placeholder="请输入文件夹名称" />
      </a-form-model-item>
      <a-form-model-item label="是否私密" prop="isPrivate">
        <a-radio-group name="radioGroup" v-model="form.isPrivate">
          <a-radio value="1">是</a-radio>
          <a-radio value="0">否</a-radio>
        </a-radio-group>
      </a-form-model-item>
    </a-form-model>
  </a-modal>
</template>

<script>
export default {
  props: {
    folderInfo: {
      type: Object,
      default: () => {}
    }
  },
  data () {
    return {
      requestLoading: false,
      form: {
        name: null,
        isPrivate: '0'
      },
      formRules: {
        name: [
          { required: true, message: '请输入文件夹名称', trigger: 'blur', whitespace: true },
          { max: 24, message: '文件夹名称最大长度不能超过24位', trigger: 'blur' }
        ],
        isPrivate: [
          { required: true, message: '请选择是否将文件夹设置为私密', trigger: 'blur' }
        ]
      }
    }
  },

  created () {
    if (this.folderInfo) {
      const { name, isPrivate, id } = this.folderInfo
      this.form = { name, isPrivate, id }
    }
  },

  methods: {
    handleOk () {
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          this.requestLoading = true
          try {
            const path = `/gimishare/api/v1/site/folder/${this.folderInfo ? 'update' : 'create'}`
            await this.$axios.post(path, this.form)
            this.$message.success(this.folderInfo ? '更新文件夹成功' : '创建文件夹成功')
            this.$emit('close-modal', true)
          } catch (error) {
            console.log(error)
          } finally {
            this.requestLoading = false
          }
        }
      })
    }
  }
}
</script>

<!-- <style scoped lang="less">

</style> -->
